const amapKey = "de8f014adc7c59857453b0bc8b7bc2a8";

Page({
    data: {
        orderList: [],
        parentId: '',
        page: 1,
        pageSize: 10,
        hasMore: true
    },

    onLoad() {
        console.log("✅ [前端] onLoad() 执行");
        const parentId = wx.getStorageSync('parentId') || 'test-parent-id';
        console.log(`🚀 获取 parentId: ${parentId}`);
        this.setData({ parentId });
        this.getOrders();
    },

    getOrders() {
        console.log("✅ [前端] getOrders() 执行");

        if (!this.data.hasMore) {
            console.warn("⚠️ 没有更多订单，停止请求");
            return;
        }

        wx.request({
            url: 'http://localhost:8081/orders/list',
            method: 'GET',
            data: {
                parentId: this.data.parentId,
                page: this.data.page,
                pageSize: this.data.pageSize
            },
            success: (res) => {
                console.log("✅ [前端] 服务器返回数据: ", res);

                if (res.data.code === 0 || res.data.code === 200) {
                    let newOrders = res.data.data.items.map(order => ({
                        orderId: order.bookingOrderId,
                        departureCoords: order.departureLongitudeLatitude || "",
                        arriveCoords: order.arriveLongitudeLatitude || "",
                        departure: "解析中...",
                        arrive: "解析中...",
                        pickUpTime: order.pickUpTime || "未知时间",
                        sendTime: order.sendTime || "未知时间",
                        totalPrice: order.totalPrice || 0
                    }));

                    console.log("✅ [前端] 订单数据解析成功: ", newOrders);

                    this.setData({
                        orderList: newOrders,
                        hasMore: newOrders.length === this.data.pageSize
                    });

                    newOrders.forEach((order, index) => {
                        if (order.departureCoords) {
                            this.getAddressFromCoordinates(order.departureCoords, (address) => {
                                let updatedOrders = this.data.orderList;
                                updatedOrders[index].departure = address;
                                this.setData({ orderList: updatedOrders });
                            });
                        }
                        if (order.arriveCoords) {
                            this.getAddressFromCoordinates(order.arriveCoords, (address) => {
                                let updatedOrders = this.data.orderList;
                                updatedOrders[index].arrive = address;
                                this.setData({ orderList: updatedOrders });
                            });
                        }
                    });

                } else {
                    console.error("❌ 获取订单失败: ", res.data);
                    wx.showToast({ title: `获取订单失败: ${res.data.message || '未知错误'}`, icon: 'none' });
                }
            },
            fail: (err) => {
                console.error("❌ 网络请求失败: ", err);
                wx.showToast({ title: '网络错误，请检查后端', icon: 'none' });
            }
        });
    },

    getAddressFromCoordinates(coordinate, callback) {
        if (!coordinate.includes(",")) {
            callback("未知地址");
            return;
        }
        const [lng, lat] = coordinate.split(",");
        console.log(`📍 [前端] 解析经纬度: ${lng}, ${lat}`);

        wx.request({
            url: `https://restapi.amap.com/v3/geocode/regeo`,
            method: "GET",
            data: { key: amapKey, location: `${lng},${lat}` },
            success: (res) => {
                console.log("✅ [前端] 逆地理编码成功: ", res);
                callback(res.data.status === "1" ? res.data.regeocode.formatted_address : "未知地址");
            },
            fail: () => {
                console.error("❌ [前端] 逆地理编码失败");
                callback("未知地址");
            }
        });
    },

    goToOrderDetail(event) {
        console.log("📌 [前端] 跳转订单详情: ", event.currentTarget.dataset.orderId);
        wx.navigateTo({ url: `/pages/order/orderDetail/orderDetail?id=${event.currentTarget.dataset.orderId}` });
    }
});
